package com.fowo.api.shein.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.model.shop.info.ShopInfoVo;
import com.fowo.api.service.ShopInfoService;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.shein.util.AESTools;
import com.fowo.api.shein.util.ApiSignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Slf4j
public class SheinAuthService {

    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private Common common;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private ShopInfoServiceImpl shopInfoService;

//    private static final String APPID = "1053683B15002A84374E91C53B2EE";
//    private static final String APP_SECRET_KEY = "790690AAA58244DC9ADC2EA30BE916CA";
//
//    private static final String TEST_SERVER = "https://openapi-test01.sheincorp.cn";
//    private static final String API_PATH = "/open-api/auth/get-by-token";

    public String getAuthorizateUrl(String state) {

        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Shein"), false);

        //跳转鉴权路径
        String authUrl = common.getAuthoritySimpleFactory(entityAuthority, "authUrl");

        //以下是get参数
        //必填
        String redirectUrl = Base64.getEncoder().encodeToString(common.getAuthoritySimpleFactory(entityAuthority, "redirectUrl").getBytes(StandardCharsets.UTF_8));//跳转回来的地址,注意用Base64编码

        //选填
//        String state = "AUTH-SHEIN-" + System.currentTimeMillis();//自定义参数,可用于回调时候的校验是否同一流程

        String appid = common.getAuthoritySimpleFactory(entityAuthority, "APPID");

        //拼接
        String url = authUrl + "?appid=" + appid + "&redirectUrl=" + redirectUrl + "&state=" + state;
        return url;
    }

    public void getByToken(String appid,String tempToken,String state) throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Shein"), false);
        String serverUrl = common.getAuthoritySimpleFactory(entityAuthority, "serverUrl");
        String apiPath = common.getAuthoritySimpleFactory(entityAuthority, "tokenPath");
        String appSecretKey = common.getAuthoritySimpleFactory(entityAuthority, "APP_SECRET_KEY");

        Date date = new Date();
        String timestamp = String.valueOf(date.getTime());
        String signString = appid + "&" + timestamp + "&" + apiPath;

        String randomKey = UUID.randomUUID().toString().substring(0, 5);
        String randomSecretKey = appSecretKey + randomKey;

        String hashValue = ApiSignUtil.hmacSha256(signString, randomSecretKey);
        String base64Value = ApiSignUtil.base64Encode(hashValue);
        String signature = randomKey + base64Value;

        String url = serverUrl + apiPath;
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        headers.add("x-lt-appid", appid);
        headers.add("x-lt-timestamp", timestamp);
        headers.add("x-lt-signature", signature);

        Map<String,Object> params = new HashMap<>();
        params.put("tempToken",tempToken);
        HttpEntity<String> httpEntity = new HttpEntity<String>(JSONUtil.toJsonStr(params), headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(url, httpEntity, Map.class);
        Map body = response.getBody();
        log.info("授权返回参数：{}",JSONUtil.toJsonStr(body));
        JSONObject jsonObject = JSONUtil.parseObj(body);

        saveOrUpdateShop(appSecretKey,jsonObject,state);

    }

    /**
     * 保存或更新店铺信息
     * @param appSecretKey
     * @param jsonObject
     * @param state
     */
    public void saveOrUpdateShop(String appSecretKey,JSONObject jsonObject,String state){

        ShopInfo shopInfo = new ShopInfo();
        if(jsonObject.getInt("code") == 0){

            final JSONObject info = jsonObject.getJSONObject("info");
            String secretKey = info.getStr("secretKey");
            String decryptSecretKey = AESTools.decrypt(secretKey, appSecretKey);

            String openKeyId = info.getStr("openKeyId");

            shopInfo.setAuthTime(new Date());
            shopInfo.setUpdateAuthTime(new Date());
            shopInfo.setSellerAuthStatus("SQ01");
            shopInfo.setRefreshToken(decryptSecretKey);
            shopInfo.setMarketplaceId(openKeyId);
        }else{
            shopInfo.setErrorAuthTime(new Date());
            shopInfo.setSellerAuthStatus("SQ02");
        }

        if(StrUtil.startWith(state,"NAME_")){
            shopInfo.setShopName(state.replaceFirst("NAME_",""));
            shopInfo.setPlatform("Shein");
            shopInfoService.save(shopInfo);
        }else if(StrUtil.startWith(state,"ID_")){
            String id = state.replaceFirst("ID_", "");
            shopInfo.setId(Long.valueOf(id));
            shopInfoService.updateById(shopInfo);
        }
    }
}
